﻿using System;
using System.IO;
using System.Xml.Linq;

namespace Raytracer.Configurations
{
    public class Configuration
    {
        private static readonly string ConfigFileDir = Environment.GetFolderPath(
            Environment.SpecialFolder.LocalApplicationData) +
            "\\Raytracer";

        private static readonly string ConfigFilePath = ConfigFileDir +
            "\\Configuration.xml";

        private FormState m_form_state;
        private LastOpenFiles m_last_open_files;
        private string m_test_generator_numbers;

        public static Configuration Instance = CreateConfiguration();

        private static Configuration CreateConfiguration()
        {
            if (new FileInfo(ConfigFilePath).Exists)
                return new Configuration(ConfigFilePath);
            else
                return new Configuration();
        }

        private Configuration()
        {
            Init();
        }

        private void Init()
        {
            m_form_state = new FormState();
            m_last_open_files = new LastOpenFiles();
        }

        public FormState FormState
        {
            get
            {
                return m_form_state;
            }
        }

        public string TestGeneratorNumbers
        {
            get
            {
                return m_test_generator_numbers;
            }
            set
            {
                m_test_generator_numbers = value;
                Save();
            }
        }

        public LastOpenFiles LastOpenFiles
        {
            get
            {
                return m_last_open_files;
            }
        }

        private Configuration(string a_file)
        {
            try
            {
                var root = XElement.Load(a_file);

                m_form_state = new FormState(root.Element("FormState"));
                m_last_open_files = new LastOpenFiles(root.Element("LastOpenFiles"));
                m_test_generator_numbers = root.Element("TestGeneratorNumbers").Value;
            }
            catch
            {
                Init();
            }
        }

        public void Save()
        {
            new DirectoryInfo(ConfigFileDir).Create();

            new XElement("Configuration",
                FormState.GetAsXml(),
                LastOpenFiles.GetAsXml(),
                new XElement("TestGeneratorNumbers", TestGeneratorNumbers)
            ).Save(ConfigFilePath);
        }
    }
}